package com.itheima.interceptor;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (true) {
            CurrentHolder.setUserId(2);
            return true;
        }

        //1. 获取请求url。
        String url = request.getRequestURL().toString();
        //2. 获取请求头中的令牌（token）。
        String jwt = request.getHeader("token");

        //3. 解析token，如果解析失败，返回错误结果（未登录）。
        try {
            Claims claims = JwtUtils.parseJWT(jwt);
            Integer id = claims.get("id", Integer.class);
            CurrentHolder.setUserId(id);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(401);
            return false;
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // log.info("TokenInterceptor完成页面渲染");
        CurrentHolder.removeUserId();
    }

}
